package ac.il.technion.c236369.hw4.core.protocol;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;

import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerResolver;

import ac.il.technion.c236369.hw4.configuration.ServerConfig;

public class HttpService extends org.apache.http.protocol.HttpService {

	private HttpRequestHandlerResolver handlerResolver;

	public HttpService(HttpProcessor proc,
			ConnectionReuseStrategy connStrategy,
			HttpResponseFactory responseFactory) {
		super(proc, connStrategy, responseFactory);
	}

	@Override
	public void setHandlerResolver(HttpRequestHandlerResolver handlerResolver) {
		this.handlerResolver = handlerResolver;
		super.setHandlerResolver(handlerResolver);
	}

	@Override
	protected void doService(HttpRequest request, HttpResponse response,
			HttpContext context) throws HttpException, IOException {
		 String target = readResourceURI(request);
		 final File file = new File(ServerConfig.getInstance().getProperties().getBase( ),
				 URLDecoder.decode(target, "UTF-8"));
		 File requestedFile = null;
		 if ( file.isDirectory( )) {
			 String[] list = file.list();
			 for ( String $ : list) {
				 if ( ServerConfig.getInstance().getProperties().getWelcomeFiles( ).contains( $))
					 requestedFile = new File( file, $);
			 }
		 } 
		 if ( requestedFile != null) {
			 String uri = request.getRequestLine().getUri() + requestedFile.getName( );
			 HttpRequestHandler handler = handlerResolver.lookup( uri);
			 if ( handler != null) {
				 handler.handle(request, response, context);
			 }
		 } else
			 super.doService(request, response, context);
	}
	
	private String readResourceURI(HttpRequest request) {
		String uri = request.getRequestLine().getUri( );
		String host = "";
		if ( request.getHeaders( HTTP.TARGET_HOST) != null) {
			host = request.getHeaders( HTTP.TARGET_HOST)[0].getValue( );
		}
		if ( !uri.contains(host))
			return uri;
		return uri.substring( uri.indexOf(host) + host.length( ), uri.length( ));
	}
}
